package com.websocket.sample.controller;

import com.websocket.sample.bean.MessageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

@Controller
public class GreetingController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/greeting")
    public MessageBean handle(MessageBean param) {
        param.setMemo(LocalDateTime.now().toString());
        return param;
    }

    @MessageMapping("/sendGreeting")
    public void sendGreeting(MessageBean param) {
        messagingTemplate.convertAndSend("/topic/greeting", param);
    }

    @MessageMapping("/exception")
    public void throwException(MessageBean param) {
        throw new RuntimeException("myExcpetion");
    }

    @MessageExceptionHandler
    public void handleException(Exception exception) {
        MessageBean messageBean = new MessageBean();
        messageBean.setContent("handle exception");
        messagingTemplate.convertAndSend("/topic/greeting", messageBean);
    }

}